<!-- 账号管理 -->
<template>
  <div class="account-management">
    <div class="title-section">
      <h2>员工管理</h2>
      <button class="btn-primary" @click="onCreate">新建</button>
    </div>

    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>关键词</label>
          <input type="text" placeholder="请输入关键词" v-model="query.keyword">
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="query.status">
            <option value="">请选择</option>
            <option :value="1">启用</option>
            <option :value="0">停用</option>
          </select>
        </div>
        <div class="filter-item">
          <label>创建时间</label>
          <el-date-picker
            v-model="createDate"
            type="date"
            placeholder="请选择创建时间"
            value-format="YYYY-MM-DD"
            clearable
            style="width: 100%"
          />
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="onSearch">搜索</button>
        <button class="btn-secondary" @click="onReset">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
            <th>员工编号</th>
            <th>员工账号</th>
            <th>手机</th>
            <th>角色</th>
            <th>部门</th>
            <th>入职时间</th>
            <th>启用</th>
            <th>启用状态</th>
            <th>创建时间</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in tableData" :key="row.userId || index">
            <td><input type="checkbox" v-model="row.selected" @change="updateSelectAll"></td>
            <td class="link-style" @click="openDetail(row)">{{ row.userCode }}</td>
            <td>{{ row.username }}</td>
            <td>{{ row.phone }}</td>
            <td>{{ row.roleName }}</td>
            <td>{{ row.deptName }}</td>
            <td>{{ row.hireDate || '-' }}</td>
            <td>{{ row.status === 1 ? '启用' : '停用' }}</td>
            <td :class="{ 'status-enable': row.status === 1, 'status-disable': row.status !== 1 }">{{ row.status === 1 ? '启用' : '停用' }}</td>
            <td>{{ row.createTime }}</td>
            <td>{{ row.remark || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 用户详情抽屉 -->
    <div v-if="detailDrawerVisible" class="drawer-mask" @click.self="closeDetail">
      <div class="drawer">
        <div class="drawer-header">
          <div>用户详情</div>
          <div class="drawer-actions">
            <button class="btn-secondary" @click="onEditFromDetail">编辑</button>
            <button class="btn-secondary" @click="onDeleteFromDetail">删除</button>
            <button class="btn-secondary" @click="closeDetail">关闭</button>
          </div>
        </div>
        <div class="drawer-body">
          <div class="detail-grid">
            <div class="item"><div class="label">员工编号</div><div class="value">{{ detail.userCode }}</div></div>
            <div class="item"><div class="label">员工账号</div><div class="value">{{ detail.username || '—' }}</div></div>
            <div class="item"><div class="label">姓名</div><div class="value">{{ detail.realName || '—' }}</div></div>
            <div class="item"><div class="label">手机</div><div class="value">{{ detail.phone || '—' }}</div></div>
            <div class="item"><div class="label">部门</div><div class="value">{{ detail.deptName || '—' }}</div></div>
            <div class="item"><div class="label">角色</div><div class="value">{{ detail.roleName || '—' }}</div></div>
            <div class="item"><div class="label">入职时间</div><div class="value">{{ detail.hireDate || '—' }}</div></div>
            <div class="item"><div class="label">状态</div><div class="value" :class="{ 'status-enable': detail.status === 1, 'status-disable': detail.status !== 1 }">{{ detail.status === 1 ? '启用' : '停用' }}</div></div>
            <div class="item item-span"><div class="label">备注</div><div class="value">{{ detail.remark || '—' }}</div></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户编辑对话框 -->
    <div v-if="editDialogVisible" class="dialog-mask">
      <div class="dialog">
        <div class="dialog-header">{{ isCreateMode ? '新建用户' : '编辑用户' }}</div>
        <div class="dialog-body">
          <div class="form-row"><label>账号</label><input v-model.trim="editForm.username" placeholder="账号"></div>
          <div class="form-row"><label>姓名</label><input v-model.trim="editForm.realName" placeholder="姓名"></div>
          <div class="form-row"><label>手机</label><input v-model.trim="editForm.phone" placeholder="手机"></div>
          <div class="form-row"><label>部门</label>
            <select v-model.number="editForm.deptId">
              <option :value="null">不选择</option>
              <option v-for="d in depts" :key="d.departmentId" :value="d.departmentId">{{ d.departmentName }}</option>
            </select>
          </div>
          <div class="form-row"><label>角色</label>
            <select v-model.number="editForm.roleId">
              <option :value="null">不选择</option>
              <option v-for="r in roles" :key="r.roleId || r.id" :value="r.roleId || r.id">{{ r.roleName || r.name }}</option>
            </select>
          </div>
          <div class="form-row"><label>入职时间</label><input v-model.trim="editForm.hireDate" placeholder="YYYY-MM-DD"></div>
          <div class="form-row"><label>状态</label>
            <select v-model.number="editForm.status">
              <option :value="1">启用</option>
              <option :value="0">停用</option>
            </select>
          </div>
          <div class="form-row"><label>备注</label><input v-model.trim="editForm.remark" placeholder="备注"></div>
        </div>
        <div class="dialog-footer">
          <button class="btn-secondary" @click="editDialogVisible = false" :disabled="editLoading">取消</button>
          <button class="btn-primary" @click="submitEdit" :disabled="editLoading">{{ editLoading ? '保存中...' : '保存' }}</button>
        </div>
      </div>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary" @click="exportSelected">导出</button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
        <button v-for="page in totalPages" :key="page" :class="{ active: currentPage === page }" @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
        <select v-model.number="pageSize" @change="onPageSizeChange">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>
  </div>
</template>

<script>
import { pageUsers, createUser, updateUser, deleteUser, listRoles, listDepts } from '@/api/user'
import { ElDatePicker } from 'element-plus'
import * as XLSX from 'xlsx'

export default {
  name: 'AccountManagement',
  components: { ElDatePicker },
  data() {
    return {
      loading: false,
      selectAll: false,
      currentPage: 1,
      pageSize: 5,
      total: 0,
      totalPages: 1,
      query: {
        keyword: '',
        status: '', // 1 启用，0 停用；空字符串表示未选择
        deptId: undefined,
        createTimeStart: '',
        createTimeEnd: '',
      },
      tableData: [],
      // 抽屉 & 编辑
      detailDrawerVisible: false,
      detail: {},
      editDialogVisible: false,
      editLoading: false,
      editForm: { userId: null, username: '', realName: '', deptId: null, roleId: null, phone: '', hireDate: '', status: 1, remark: '' },
      isCreateMode: false,
      roles: [],
      depts: [],
      optionsLoading: false,
      // 单日日期筛选
      createDate: '',
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    openDetail(row) {
      this.detail = { ...row }
      this.detailDrawerVisible = true
    },
    closeDetail() { this.detailDrawerVisible = false },
    async onCreate() {
      // 进入新建模式，重置表单
      this.isCreateMode = true
      this.editForm = { userId: null, username: '', realName: '', deptId: null, roleId: null, phone: '', hireDate: '', status: 1, remark: '' }
      await this.loadOptions()
      this.editDialogVisible = true
    },
    async onEditFromDetail() {
      this.isCreateMode = false
      this.editForm = {
        userId: this.detail.userId,
        username: this.detail.username || '',
        realName: this.detail.realName || '',
        deptId: this.detail.deptId ?? null,
        roleId: this.detail.roleId ?? null,
        phone: this.detail.phone || '',
        hireDate: this.detail.hireDate || '',
        status: this.detail.status ?? 1,
        remark: this.detail.remark || '',
      }
      await this.loadOptions()
      this.editDialogVisible = true
    },
    async onDeleteFromDetail() {
      if (!this.detail || !this.detail.userId) return
      if (!confirm('确认删除该用户吗？')) return
      try {
        await deleteUser(this.detail.userId)
        this.closeDetail()
        this.currentPage = 1
        await this.fetchData()
      } catch (e) { /* 全局拦截器已有提示 */ }
    },
    async loadOptions() {
      try {
        this.optionsLoading = true
        const [rolesRes, deptsRes] = await Promise.all([
          listRoles(),
          listDepts(),
        ])
        this.roles = Array.isArray(rolesRes?.data?.data) ? rolesRes.data.data : (rolesRes?.data || [])
        const deptList = deptsRes?.data?.data?.records || deptsRes?.data?.data || []
        this.depts = Array.isArray(deptList) ? deptList : []
      } finally { this.optionsLoading = false }
    },
    async submitEdit() {
      try {
        this.editLoading = true
        const payload = { ...this.editForm }
        if (this.isCreateMode || !payload.userId) {
          // 新建用户
          await createUser(payload)
        } else {
          // 编辑用户
          await updateUser(payload)
        }
        this.editDialogVisible = false
        this.detailDrawerVisible = false
        this.currentPage = 1
        await this.fetchData()
      } finally {
        this.editLoading = false
      }
    },
    async fetchData() {
      try {
        this.loading = true
        const params = { pageNum: this.currentPage, pageSize: this.pageSize }
        // 账号关键字
        if (this.query.keyword) params.keyword = this.query.keyword
        if (this.query.status !== '') params.status = Number(this.query.status)
        // 部门查询已取消
        // 日期筛选（单日：两端同一天）
        if (this.createDate) {
          params.createTime1 = this.createDate
          params.createTime2 = this.createDate
        }
        const res = await pageUsers(params)
        const payload = res?.data
        const data = payload?.data || { total: 0, records: [] }
        this.total = Number(data.total || 0)
        this.totalPages = Math.max(1, Math.ceil(this.total / this.pageSize))
        this.tableData = (data.records || []).map(r => ({
          selected: false,
          userId: r.userId,
          username: r.username,
          userCode: r.userCode,
          deptId: r.deptId,
          phone: r.phone,
          realName: r.realName,
          hireDate: r.hireDate,
          status: r.status,
          createTime: r.createTime,
          remark: r.remark,
          roleName: r.roleName,
          deptName: r.deptName,
          roleId: r.roleId,
        }))
        // 同步全选状态
        this.updateSelectAll()
      } catch (e) {
        // 错误提示已由 http 拦截器处理
      } finally {
        this.loading = false
      }
    },
    onSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    onReset() {
      this.query.keyword = ''
      this.query.status = ''
      // 部门查询已取消
      this.query.createTimeStart = ''
      this.query.createTimeEnd = ''
      this.createDate = ''
      this.currentPage = 1
      this.fetchData()
    },
    onPageSizeChange() {
      this.currentPage = 1
      this.fetchData()
    },
    toggleSelectAll() { this.tableData.forEach(r => { r.selected = this.selectAll; }); },
    updateSelectAll() { this.selectAll = this.tableData.length > 0 && this.tableData.every(r => r.selected); },
    prevPage() { if (this.currentPage > 1) { this.currentPage--; this.fetchData() } },
    nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; this.fetchData() } },
    goToPage(page) { if (page !== this.currentPage) { this.currentPage = page; this.fetchData() } },
    exportSelected() {
      const selected = this.tableData.filter(r => r.selected)
      if (!selected.length) {
        alert('请选择要导出的数据')
        return
      }
      const rows = selected.map(r => ({
        '员工编号': r.userCode || '',
        '员工账号': r.username || '',
        '手机': r.phone || '',
        '角色': r.roleName || '',
        '部门': r.deptName || '',
        '入职时间': r.hireDate || '',
        '启用状态': r.status === 1 ? '启用' : '停用',
        '创建时间': r.createTime || '',
        '备注': r.remark || ''
      }))
      const ws = XLSX.utils.json_to_sheet(rows)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '员工')
      const date = new Date().toISOString().slice(0, 10)
      XLSX.writeFile(wb, `员工_导出_${date}.xlsx`)
      alert(`已导出选中的 ${selected.length} 条记录`)
    }
  }
}
</script>

<style scoped>
.account-management { padding: 24px; background-color: #f5f7fa; }
.title-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.title-section h2 { font-size: 20px; font-weight: bold; }
.controls-section { display: flex; align-items: center; gap: 16px; padding: 16px 20px; background-color: #fff; border-radius: 12px; margin-bottom: 16px; box-shadow: 0 2px 12px rgba(0,0,0,0.04); }
.filters { display: flex; align-items: center; gap: 20px; flex: 1; }
.filter-item { display: flex; flex-direction: column; align-items: stretch; gap: 6px; }
.filters .filter-item { width: 280px; }
.filters .filter-item:nth-child(3) { width: 320px; }
.filter-item label { font-size: 13px; color: #606266; }
.filter-item input, .filter-item select { padding: 10px 12px; border: 1px solid #dcdfe6; border-radius: 8px; width: 100%; box-sizing: border-box; height: 38px; line-height: 38px; }
 /* make Element Plus date editor full width */
.filter-item :deep(.el-date-editor) { width: 100%; }
.filter-item :deep(.el-input__wrapper) { border-radius: 8px; }
.date-input { max-width: 240px; }
.to-sep { margin: 0 8px; color: #999; }
.actions { display: flex; gap: 12px; align-items: center; justify-self: end; align-self: end; white-space: nowrap; }
.btn-primary { background-color: #409eff; color: white; border: none; padding: 10px 18px; border-radius: 8px; cursor: pointer; box-shadow: 0 2px 8px rgba(64,158,255,0.25); transition: all .2s ease; }
.btn-primary:hover { background-color: #3a8be0; transform: translateY(-1px); box-shadow: 0 6px 16px rgba(64,158,255,0.25); }
.btn-secondary { background-color: #fff; color: #606266; border: 1px solid #dcdfe6; padding: 10px 18px; border-radius: 8px; cursor: pointer; transition: all .2s ease; }
.btn-secondary:hover { border-color: #c0c4cc; color: #303133; }
.table-section { background-color: #fff; padding: 16px; border-radius: 10px; overflow: auto; }
table { width: 100%; border-collapse: collapse; min-width: 1200px; font-size: 14.5px; }
th, td { padding: 20px 22px; text-align: left; border-bottom: 1px solid #ebeef5; vertical-align: middle; line-height: 1.8; white-space: nowrap; }
thead th { position: sticky; top: 0; background-color: #f8f9fa; z-index: 1; }
.link-style { color: #409eff; cursor: pointer; }
.link-style:hover { text-decoration: underline; }
tbody tr:hover { background: #f7fbff; }
.status-enable { color: #2eaa3b; }
.status-disable { color: #f44336; }
.footer-section { display: flex; justify-content: space-between; align-items: center; margin-top: 16px; background-color: #fff; padding: 12px 20px; border-radius: 12px; flex-wrap: wrap; row-gap: 10px; box-shadow: 0 2px 12px rgba(0,0,0,0.04); }
.footer-left { display: flex; align-items: center; gap: 10px; }
.pagination { display: flex; align-items: center; gap: 6px; }
.pagination button { padding: 6px 10px; border: 1px solid #dcdfe6; background-color: #fff; cursor: pointer; border-radius: 6px; }
.pagination button.active { background-color: #409eff; color: white; border-color: #409eff; }
.pagination select { padding: 6px; border: 1px solid #dcdfe6; border-radius: 6px; }

/* Column widths to increase space per column (updated after removing 班组列) */
thead th:nth-child(1), tbody td:nth-child(1) { width: 56px; }
thead th:nth-child(2), tbody td:nth-child(2) { width: 150px; }
thead th:nth-child(3), tbody td:nth-child(3) { width: 180px; }
thead th:nth-child(4), tbody td:nth-child(4) { width: 150px; }
thead th:nth-child(5), tbody td:nth-child(5) { width: 160px; }
thead th:nth-child(6), tbody td:nth-child(6) { width: 160px; }
thead th:nth-child(7), tbody td:nth-child(7) { width: 170px; }
thead th:nth-child(8), tbody td:nth-child(8) { width: 170px; }
thead th:nth-child(9), tbody td:nth-child(9) { width: 120px; }
thead th:nth-child(10), tbody td:nth-child(10) { width: 130px; }
thead th:nth-child(11), tbody td:nth-child(11) { width: 200px; }
thead th:nth-child(12), tbody td:nth-child(12) { width: 260px; }

/* 抽屉与对话框样式 */
.drawer-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.2); z-index: 1000; }
.drawer { position: absolute; top: 0; right: 0; height: 100%; width: 520px; background: #fff; box-shadow: -2px 0 18px rgba(0,0,0,0.15); display: flex; flex-direction: column; border-top-left-radius: 10px; border-bottom-left-radius: 10px; }
.drawer-header { display: flex; justify-content: space-between; align-items: center; padding: 14px 16px; border-bottom: 1px solid #eee; font-weight: 600; }
.drawer-body { padding: 16px; overflow: auto; }
.detail-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 16px; }
.item { background: #fafafa; border: 1px solid #f0f0f0; border-radius: 6px; padding: 10px 12px; }
.item-span { grid-column: 1 / -1; }
.label { font-size: 12px; color: #909399; margin-bottom: 6px; }
.value { font-size: 14px; color: #303133; }
.drawer-actions { display: flex; align-items: center; gap: 8px; }

.dialog-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.35); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.dialog { width: 520px; background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 12px 28px rgba(0,0,0,0.18); display: flex; flex-direction: column; }
.dialog-header { padding: 14px 16px; font-weight: 600; border-bottom: 1px solid #eee; }
.dialog-body { padding: 16px; }
.dialog-footer { padding: 12px 16px; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #eee; }
.form-row { margin-bottom: 12px; display: flex; align-items: center; gap: 10px; }
.form-row label { width: 120px; text-align: right; color: #606266; }
.form-row input, .form-row select { flex: 1; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; }

/* Better focus style for inputs/selects */
.filter-item input:focus, .filter-item select:focus { outline: none; border-color: #409eff; box-shadow: 0 0 0 3px rgba(64,158,255,0.12); }

@media (max-width: 992px) {
  .controls-section { flex-direction: column; align-items: stretch; }
  .filters { flex-wrap: wrap; }
  .filters .filter-item, .filters .filter-item:nth-child(3) { width: 100%; }
  .date-input { max-width: 100%; }
}

@media (max-width: 600px) {
  table { min-width: 800px; }
}
</style>
